package com.zw.transition.config.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.zw.transition.annotation.RepeatCommit;
import com.zw.transition.common.JsonResult;
import com.zw.transition.util.ServletUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Description: 重复提交拦截器
 *
 * @author: China.sgl
 * @Date: 2020/9/22 13:34
 */
@Component
public abstract class AbstractRepeatCommitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatCommit repeatSubmit = method.getAnnotation(RepeatCommit.class);
            if (repeatSubmit == null) {
                return true;
            }
            if (isRepeatSubmit(request)) {
                ServletUtils.renderString(response, new ObjectMapper().writeValueAsString(JsonResult.fail("不允许重复提交，请稍后再试")));
                return false;
            }
        }
        return true;
    }

    /**
     * 验证是否重得利提交交由具体实现类
     *
     * @param request request
     * @return boolean
     * @throws Exception Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request) throws Exception;
}
